import java.util.*;
import java.text.SimpleDateFormat;
import groovy.json.JsonOutput

class DingPost {

    String apkQrCode = "https://baike.baidu.com/item/%E8%A5%BF%E6%B9%96/4668821"
    def atMobiles = []
    String requestUrl = "https://open.feishu.cn/open-apis/bot/v2/hook/4b2441c0-79f3-44ee-89bc-5a806a845c38";
    String NO_NEW_CHANGE = "";

    def getContent(def buildResult, def jobName, def buildNumber, def gitBranch,
                   def buildUrl, def changeString,appVersion,androidUrl,iosUrl,appEnv) {
        def content;
        if (NO_NEW_CHANGE == changeString || gitBranch == "master")
            return "";

        if (buildResult == "SUCCESS") {
            content = getBuildSuccessContent(jobName, buildNumber, gitBranch,
                    buildUrl, changeString,appVersion,androidUrl,iosUrl,appEnv)
        } else if (buildResult == "ABORTED") {
            content = getBuildAbortedContent(jobName, buildNumber, gitBranch,
                    buildUrl, changeString,appEnv,appVersion)
        } else {
            content = getBuildFailContent(jobName, buildNumber, gitBranch,
                    buildUrl, changeString,appEnv,appVersion)
        }
        return content;
    }


    def getBuildFailContent(jobName, buildNumber, gitBranch,
                            buildUrl, changeString,appEnv,appVersion) {

        String content = "### 《" + jobName;
        content += "》构建失败 :: \n\n ####" + appEnv
        content += "-" + appVersion
        content += "(" +buildNumber
        content += ")\n\n "
        content += getNowTime() + " 构建\n\n[查看详情]("
        content += buildUrl + ")"
        return content;
    }

    def getBuildAbortedContent(jobName, buildNumber, gitBranch,
                               buildUrl, changeString,appEnv,appVersion) {
        String content = "### 《" + jobName;
        content += "》构建被终止 : \n\n ####" + appEnv
        content += "-" + appVersion
        content += "(" +buildNumber
        content += ")\n\n "
        content += getNowTime() + " 构建\n\n[查看详情]("
        content += buildUrl + ")"
        return content;
    }

    def getBuildSuccessContent(jobName, buildNumber, gitBranch,
                               buildUrl, changeString,appVersion,androidUrl,iosUrl,appEnv) {
        String content = "### 《" + jobName;
        content += "》构建成功 :\n\n #### " + appEnv
        content += "-" + appVersion
        content += "(" +buildNumber
        content += ")\n\n #### 更新记录：\n\n" + changeString
        // content += "\n\n![](" + apkQrCode+ ")"
        content += "\n\n" + getNowTime()
        content += " 构建\n\n"
        content += " [  APK  ](" + androidUrl
        content += ")"+" [  IPA  ]("
        content += iosUrl+")"
        content += " [查看详情](" + buildUrl
        content += ")"
        return content;
    }


    //发送钉钉消息
    def postToDing(String content) {
        def at = new At();
        at.atMobiles = atMobiles;
        MarkdownRequest request = new MarkdownRequest(new Markdown("", content), at);
        def jsonOut = new JsonOutput();
        def requestString = jsonOut.toJson(request)
        return post(requestString);
    }


    //发送消息到飞书
    def postToFeishu(String content) {
        def requestBody = [
                msg_type: "interactive",
                card    : [
                        schema: "2.0",
                        config: [
                                update_multi: true,
                                style       : [
                                        text_size: [
                                                normal_v2: [
                                                        "default": "normal",
                                                        pc       : "normal",
                                                        mobile   : "heading"
                                                ]
                                        ]
                                ]
                        ],
                        body  : [
                                direction: "vertical",
                                padding  : "12px 12px 12px 12px",
                                elements : [
                                        [
                                                tag    : "markdown",
                                                content: content
                                        ]
                                ]
                        ],
                        header: [
                                template: "blue",
                                title   : [
                                        tag    : "plain_text",
                                        content: "Zelos Jenkins 通知"
                                ]
                        ]
                ],
        ]
        def jsonOut = new JsonOutput();
        def requestString = jsonOut.toJson(requestBody)
        return post(requestString);
    }


    def post(String body) {
        def connection = new URL(requestUrl).openConnection()
        connection.setRequestMethod('POST')
        connection.doOutput = true
        connection.setRequestProperty('Content-Type', 'application/json')

        def writer = new OutputStreamWriter(connection.outputStream)
        writer.write(body);
        writer.flush()
        writer.close()
        connection.connect()

        def respText = connection.content.text
        return respText;
    }


    def getChangeStringWithPreviousFail(def currentBuild) {
        def currentChange = getChangeString(currentBuild.changeSets);
        def prevBuild = currentBuild.previousBuild;

        if (prevBuild == null || prevBuild.result == "SUCCESS") {
            return currentChange;
        } else {
            return getChangeStringWithPreviousFail(prevBuild) + currentChange;
        }
    }

    def getChangeString(def changeLogSets) {
        def MAX_MSG_LEN = 100
        def changeString = ""


        for (int i = 0; i < changeLogSets.size(); i++) {
            def entries = changeLogSets[i].items
            for (int j = 0; j < entries.length; j++) {
                def entry = entries[j]
                def truncated_msg = entry.msg.take(MAX_MSG_LEN)
                changeString += " - ${truncated_msg} [${entry.author}]\n"
            }
        }
        if (!changeString) {
            changeString = NO_NEW_CHANGE
        }
        return changeString
    }

    def getNowTime() {
        def str = "";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar lastDate = Calendar.getInstance();
        str = sdf.format(lastDate.getTime());
        return str;
    }
}

DingPost dingPost = new DingPost();
return  dingPost;
//def content = dingPost.getContent("SUCCESS", "ExampleJob", 123, "feature-branch",
//        "http://example.com/job/ExampleJob/123/",
//        "Commit message here");
//println content;
//def result = dingPost.postToFeishu(content);
//println result;

class Markdown {
    String title;
    String text;

    Markdown(String title, String content) {
        this.text = content;
        this.title = title;
    }
}

class At {
    String[] atMobiles;
    boolean isAtAll = false;

}

class MarkdownRequest {
    String msgtype = "markdown";
    Markdown markdown;
    At at;

    MarkdownRequest(Markdown markdown, At at) {
        this.markdown = markdown;
        this.at = at;
    }
}